/******************************************************************************

    Simple Authentication and Authorisation System (SAAS)

    pkt-auth.c

    Copyright (C) 2011  Josh Goes


    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    If you require a mailing address for this software, please send your
    mail to the following address:
        SAAS
        GPO Box 2973
        BRISBANE QLD 4001
        AUSTRALIA

******************************************************************************/



#include "saas-build.h"

#include <string.h>
#include <unistd.h>


uint16_t pkt_req_authenticate( saas_t *inst , uint32_t *trans_id , uint8_t *pkt , uint16_t *pkt_len , const uint8_t *username , const uint8_t *password )
{
	uint8_t  payload[SAAS_MAX_PKT_LEN];
	uint8_t  username_len = 0;
	char hostname[256];

	memset( payload , 0 , sizeof( payload ) );
	username_len = strlen( (char *) username );
	memset( payload , username_len , 1 );
	memcpy( payload + 1 , username , username_len );
	sha512dual( payload + 1 + username_len , inst->pw_salt , inst->pw_salt_len , password , strlen( (char *) password ) );

	// now we call pkt_pack to pack it altogether into a single packet.
	pkt_req( inst , trans_id , pkt , pkt_len , SAAS_MAGIC_REQ , SAAS_PKT_TYPE_AUTHENTICATE , payload , 1 + username_len + 64 + 1 + strlen( hostname ) );

	return SAAS_OP_SUCCESS;
}



uint16_t pkt_resp_authenticate( saas_t *inst , uint32_t trans_id , uint8_t *pkt , uint16_t pkt_len , uint32_t *pass_expire )
{
	uint16_t ret = pkt_resp( inst , trans_id , pkt , pkt_len );
	if ( ret != SAAS_OP_SUCCESS )
		return ret;

	pkt_hdr_t *hdr = (pkt_hdr_t *) pkt;
	if ( hdr->type == SAAS_PKT_TYPE_AUTHENTICATE && hdr->payload_len >= 2 )
	{
		// the right kind of response we're looking for.
		uint16_t  *fret       = (uint16_t  *)  pkt + ( sizeof( pkt_hdr_t ) / 2 );
		*fret = u16fromnet( *fret );
		if ( *fret == SAAS_OP_SUCCESS )
			*pass_expire = u32fromnet( *( (uint32_t *)  pkt + ( sizeof( pkt_hdr_t ) / 4 ) + 1 ) );
		return *fret;
	}

	return SAAS_OP_DECRYPT_ERROR;
}


